package com.ds.lens.flink.monitor.eventsinkjob.function.notify.mail;

import com.google.gson.Gson;
import com.ds.lens.data.common.constant.EventSourceEnum;
import com.ds.lens.data.common.document.MailConfig;
import com.ds.lens.data.common.document.dto.MonitorEvent;
import com.ds.lens.data.common.util.MailUtil;
import com.ds.lens.flink.monitor.eventsinkjob.function.notify.MonitorEventNotifier;

/**
 * @author WeiShaoying
 * @date 2020/2/11 下午4:12
 */
public class MailMonitorEventNotifier implements MonitorEventNotifier<MonitorEvent, String> {
    private MailConfig mailConfig;

    public MailMonitorEventNotifier(MailConfig mailConfig) {
        this.mailConfig = mailConfig;
    }

    @Override
    public String send(MonitorEvent data) throws Exception {
        MailUtil.sendHTMLMail(mailConfig, data.getNotify().getContent(), customTitle(data),
                new Gson().fromJson(data.getNotify().getChannelContent(), Mail.class).getTo());
        return null;
    }

    private String customTitle(MonitorEvent event) {
        if (EventSourceEnum.EXTERNAL_EVENT.equals(event.getEventSourceEnum())) {
            return "External alert " + event.getNotify().getTitle();
        }
        StringBuilder builder = new StringBuilder();
        builder.append("Lens monitor ")
                .append(event.getMonitorName())
                .append(" generates a level")
                .append(event.getTriggered().getState().name())
                .append(" event ")
                .append(event.getNotify().getTitle());
        return builder.toString();
    }
}
